﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Diagnostics;

using LibIpMsgNet;

namespace IpMsgNet
{
    public partial class frmMain : Form
    {
        private TIpMessenger messenger = new TIpMessenger();

        TraceForm trace = new TraceForm();

        public frmMain()
        {
            InitializeComponent();

            messenger.MessageReceived += new TMessageReceivedHandler(messenger_MessageReceived);

            trace.Show();
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            try
            {
                /*
                MsgMng mng = new MsgMng((ulong)Dns.GetHostEntry(Environment.MachineName).AddressList[0].Address, 0x0979);
                mng.Send(0xffffffff, 0x0979, IPMSG_DEF.IPMSG_BR_ENTRY, "aaa", "bbb");

                ///
                string[] sip = tbIp.Text.Split('.');
                byte[] ip = new byte[4] {
                    Convert.ToByte(sip[0]),
                    Convert.ToByte(sip[1]),
                    Convert.ToByte(sip[2]),
                    Convert.ToByte(sip[3]),
                };
                // 
                

                IPAddress addr = IPAddress.Parse(tbIp.Text);

                long cmd = Convert.ToInt64(tbCmd.Text.Trim());

                mng.Send((ulong)addr.Address, 0x0979, (ulong)cmd, tbMsg.Text, tbExMsg.Text);

                MsgBuf buf = new MsgBuf(null);

                //while (buf.msgBuf.Length<=0)
                while (!mng.Recv(ref buf)) { }

                //{ 
                    MessageBox.Show( Utils.ByteArrayToString(buf.msgBuf));
                //}
                */

                THostSub host = new THostSub();
                host.EndPoint.Address = IPAddress.Parse(tbIp.Text);
                host.EndPoint.Port = 0x0979;

                messenger.SendMessage(host.EndPoint, tbMsg.Text);


            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.StackTrace + ex.Message);
            }
        
        }

        private void messenger_MessageReceived(object sender, EventArgs e)
        {
            TMessageBuffer buf = sender as TMessageBuffer;
            MessageBox.Show(buf.TextMessage());
        }
    }
}
